﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Server;

namespace EAGL.Core
{
    /// <summary>
    /// Basic serialization utility class that uses PersistStream to do its work
    /// </summary>
    public class TPersistStreamSerializer
    {
        public byte[] Serialize(IPersistStream ps)
        {
            IXMLStream xmlStream = new XMLStreamClass();
            ps.Save(xmlStream as IStream, 0);
            byte[] bs = xmlStream.SaveToBytes();
            return bs;
        }

        public void Deserialize(byte[] bytes, ref IPersistStream ps)
        {
            IXMLStream xmlStream = new XMLStreamClass();
            xmlStream.LoadFromBytes(ref bytes);
            ps.Load(xmlStream as IStream);
        }

        public IPersistStream Deserialize(byte[] bytes, IServerContext context, string CLSID)
        {
            IXMLStream xmlStream = (IXMLStream)context.CreateObject("esriSystem.XmlStream");
            IPersistStream ps = (IPersistStream)context.CreateObject(CLSID);
            xmlStream.LoadFromBytes(ref bytes);
            ps.Load((IStream)xmlStream);
            return ps;
        }

        public void SaveToFile(IPersistStream ps, string fileName)
        {
            IXMLStream xmlStream = new XMLStreamClass();
            ps.Save(xmlStream as IStream, 0);
            xmlStream.SaveToFile(fileName);
        }

        public void LoadFromFile(string fileName, ref IPersistStream ps)
        {
            IXMLStream xmlStream = new XMLStreamClass();
            xmlStream.LoadFromFile(fileName);
            ps.Load(xmlStream as IStream);
        }
    }
}
